<template>
  <div class="register-container">
    <div class="register-content">
      <div class="register-card">
        <div class="register-header">
          <img src="../assets/images/logo.png" alt="Logo" class="register-logo" />
          <h2>创建新账号</h2>
          <p>加入懂车之家，开启您的汽车销售之旅</p>
        </div>
        
        <el-form :model="registerForm" :rules="rules" ref="registerFormRef" class="register-form" label-width="80px">
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="用户名" prop="username">
                <el-input 
                  v-model="registerForm.username" 
                  placeholder="请输入用户名"
                  :prefix-icon="User"
                />
              </el-form-item>
            </el-col>
            
            <el-col :span="24">
              <el-form-item label="密码" prop="password">
                <el-input 
                  v-model="registerForm.password" 
                  type="password" 
                  placeholder="请输入密码"
                  :prefix-icon="Lock"
                  show-password
                />
              </el-form-item>
            </el-col>
            
            <el-col :span="24">
              <el-form-item label="确认密码" prop="confirmPassword">
                <el-input 
                  v-model="registerForm.confirmPassword" 
                  type="password" 
                  placeholder="请再次输入密码"
                  :prefix-icon="Lock"
                  show-password
                />
              </el-form-item>
            </el-col>
            
            <el-col :span="24">
              <el-form-item label="昵称" prop="nickname">
                <el-input 
                  v-model="registerForm.nickname" 
                  placeholder="请输入昵称（选填）"
                  :prefix-icon="UserFilled"
                />
              </el-form-item>
            </el-col>
            
            <el-col :span="24">
              <el-form-item label="手机号" prop="phone">
                <el-input 
                  v-model="registerForm.phone" 
                  placeholder="请输入手机号（选填）"
                  :prefix-icon="Phone"
                />
              </el-form-item>
            </el-col>
            
            <el-col :span="24">
              <el-form-item label="邮箱" prop="email">
                <el-input 
                  v-model="registerForm.email" 
                  placeholder="请输入邮箱（选填）"
                  :prefix-icon="Message"
                />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-form-item>
            <el-button 
              type="primary" 
              :loading="loading" 
              class="register-button" 
              @click="handleRegister"
            >
              立即注册
            </el-button>
          </el-form-item>
          
          <div class="register-options">
            <router-link to="/login" class="login-link">
              已有账号？立即登录
            </router-link>
          </div>
        </el-form>
      </div>
      
      <div class="register-footer">
        <p>© {{ new Date().getFullYear() }} 懂车之家 - 专业的汽车销售管理系统</p>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '../store/user'
import { ElMessage } from 'element-plus'
import { User, UserFilled, Lock, Phone, Message } from '@element-plus/icons-vue'

// 状态
const registerForm = reactive({
  username: '',
  password: '',
  confirmPassword: '',
  nickname: '',
  phone: '',
  email: ''
})

// 自定义校验规则
const validatePass = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请输入密码'))
  } else if (value.length < 6) {
    callback(new Error('密码长度不能小于6位'))
  } else {
    if (registerForm.confirmPassword !== '') {
      registerFormRef.value.validateField('confirmPassword')
    }
    callback()
  }
}

const validateConfirmPass = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请再次输入密码'))
  } else if (value !== registerForm.password) {
    callback(new Error('两次输入的密码不一致'))
  } else {
    callback()
  }
}

const validatePhone = (rule, value, callback) => {
  if (value === '') {
    callback()
  } else if (!/^1[3-9]\d{9}$/.test(value)) {
    callback(new Error('请输入正确的手机号'))
  } else {
    callback()
  }
}

const validateEmail = (rule, value, callback) => {
  if (value === '') {
    callback()
  } else if (!/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(value)) {
    callback(new Error('请输入正确的邮箱地址'))
  } else {
    callback()
  }
}

const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在3到20个字符之间', trigger: 'blur' }
  ],
  password: [
    { validator: validatePass, trigger: 'blur' }
  ],
  confirmPassword: [
    { validator: validateConfirmPass, trigger: 'blur' }
  ],
  nickname: [
    { max: 20, message: '昵称长度不能超过20个字符', trigger: 'blur' }
  ],
  phone: [
    { validator: validatePhone, trigger: 'blur' }
  ],
  email: [
    { validator: validateEmail, trigger: 'blur' }
  ]
}

const registerFormRef = ref(null)
const loading = ref(false)
const router = useRouter()
const userStore = useUserStore()

// 方法
const handleRegister = async () => {
  if (!registerFormRef.value) return
  
  await registerFormRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      
      try {
        // 构建注册数据，移除确认密码字段
        const registerData = {
          username: registerForm.username,
          password: registerForm.password,
          nickname: registerForm.nickname || '',
          phone: registerForm.phone || '',
          email: registerForm.email || ''
        }
        
        const { success, message, data } = await userStore.register(registerData)
        
        if (success) {
          ElMessage.success('注册成功，请登录')
          router.push('/login')
        } else {
          ElMessage.error(message || '注册失败')
        }
      } catch (error) {
        ElMessage.error('注册过程中发生错误')
        console.error(error)
      } finally {
        loading.value = false
      }
    }
  })
}
</script>

<style scoped>
.register-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background: linear-gradient(135deg, #f0f2f5, #e6e9ef);
  padding: 40px 0;
  position: relative;
  overflow: hidden;
}

.register-container::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100" viewBox="0 0 100 100"><rect fill="rgba(64, 158, 255, 0.03)" width="50" height="50" x="0" y="0"></rect><rect fill="rgba(64, 158, 255, 0.03)" width="50" height="50" x="50" y="50"></rect></svg>');
  opacity: 0.5;
  z-index: 0;
}

.register-content {
  width: 100%;
  max-width: 600px;
  z-index: 1;
  animation: fadeIn 0.8s ease-in-out;
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(20px); }
  to { opacity: 1; transform: translateY(0); }
}

.register-card {
  background-color: #fff;
  border-radius: 12px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
  padding: 40px;
  margin-bottom: 20px;
  transition: all 0.3s ease;
}

.register-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 15px 35px rgba(0, 0, 0, 0.15);
}

.register-header {
  text-align: center;
  margin-bottom: 30px;
}

.register-logo {
  width: 60px;
  height: 60px;
  margin-bottom: 20px;
}

.register-header h2 {
  font-size: 28px;
  color: var(--text-primary);
  margin-bottom: 10px;
  font-weight: 600;
}

.register-header p {
  font-size: 16px;
  color: var(--text-secondary);
  max-width: 400px;
  margin: 0 auto;
}

.register-form {
  margin-top: 20px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: var(--text-regular);
  font-size: 15px;
}

:deep(.el-input__wrapper) {
  padding: 12px 15px;
  border-radius: 8px;
  box-shadow: 0 0 0 1px var(--border-color) inset;
  transition: all 0.3s ease;
}

:deep(.el-input__wrapper:hover) {
  box-shadow: 0 0 0 1px var(--primary-color) inset;
}

:deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 1px var(--primary-color) inset;
  outline: none;
}

/* 移除输入框焦点时的默认轮廓 */
:deep(.el-input__wrapper:focus) {
  outline: none;
  box-shadow: none;
}

:deep(.el-input__inner:focus) {
  outline: none;
  box-shadow: none;
}

/* 通用焦点样式重置 */
:deep(*:focus) {
  outline: none !important;
  box-shadow: none !important;
}

:deep(.el-input) {
  outline: none;
}

:deep(.el-input:focus) {
  outline: none;
  box-shadow: none;
}

:deep(.el-input__inner) {
  border: none;
  outline: none;
}

:deep(.el-input.is-focus) {
  outline: none;
  box-shadow: none;
}

:deep(.el-input--password .el-input__wrapper) {
  outline: none;
  box-shadow: 0 0 0 1px var(--border-color) inset;
}

:deep(.el-input--password .el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 1px var(--primary-color) inset;
  outline: none;
}

:deep(.el-input--password .el-input__wrapper:focus) {
  outline: none;
  box-shadow: none;
}

:deep(.el-form-item) {
  margin-bottom: 25px;
  transition: all 0.3s ease;
}

:deep(.el-form-item:hover) {
  transform: translateX(5px);
}

.register-button {
  width: 100%;
  height: 48px;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 500;
  letter-spacing: 1px;
  background: linear-gradient(135deg, #409EFF, #3a8ee6);
  border: none;
  transition: all 0.3s ease;
}

.register-button:hover {
  background: linear-gradient(135deg, #66b1ff, #409EFF);
  box-shadow: 0 5px 15px rgba(64, 158, 255, 0.3);
  transform: translateY(-2px);
}

.register-options {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.login-link {
  font-size: 15px;
  color: var(--primary-color);
  text-decoration: none;
  transition: all 0.3s ease;
  position: relative;
}

.login-link::after {
  content: '';
  position: absolute;
  bottom: -2px;
  left: 0;
  width: 0;
  height: 2px;
  background-color: var(--primary-color);
  transition: width 0.3s ease;
}

.login-link:hover::after {
  width: 100%;
}

.register-footer {
  text-align: center;
  color: var(--text-secondary);
  font-size: 14px;
}

/* 响应式布局 */
@media (max-width: 768px) {
  .register-content {
    width: 95%;
  }
  
  .register-card {
    padding: 30px 20px;
  }
  
  :deep(.el-form-item__label) {
    padding-bottom: 5px;
  }
  
  :deep(.el-form) {
    --el-form-label-position: top;
  }
}
</style>